JavaScript Promises Essentials by Sarieddine Rami

JavaScript Promises Essentials by Sarieddine Rami

Author:Sarieddine, Rami [Sarieddine, Rami]
Language: eng
Format: azw3, epub, mobi
Publisher: Packt Publishing
Published: 2014-09-25T04:00:00+00:00


In the previous code sample, we first declare a variable called catPromise to hold the category of the promise. Next, we declare a function called getCategory(i) that takes the values of i as a parameter; inside this function, and we set catPromise to the JSON data retrieved by the getData(jsonCategoryUrl) function; however, using the || (or) operator, we can first check whether the catPromise object has a value so that we don't fetch the category JSON file again, but only once. When we call getCategory with the value 0, it will retrieve the first category; after this, it will return the next category with getCategory(1) and pass it to the last then call. In this way, we won't download the category JSON file until getCategory is called; however often we call the getCategory function again, though, we will not need to redownload the category JSON file; rather, we will reuse it since it will be called again in the sequence of operations. As the getCategory function returns another promise object, it allows you to have promise-pipelining, where we have the result from the first operation getting passed to the subsequent one. Also, the important feature that this sample shows is that, if the function provided to then returns a new promise, the promise returned by then will not be fulfilled until the promise returned by that function is fulfilled, thereby queuing the asynchronous operation in that chain of promises.

In addition, the previous sample clearly shows how promises address the traditional callback model and the pyramid code that it generates.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.